class UserSessionsController < ApplicationController

  before_filter :require_no_user, :only => [:new, :create]
  before_filter :require_user, :only => :destroy
  def new
    @user_session = UserSession.new
  end

  def create
    entry = Entry.new
    begin
      @user_session = UserSession.new(params[:user_session])
      entry.login = @user_session.login
      
      entry.action = 'login'
      if @user_session.save
        flash[:notice] = "Login successful!"
        
        # load user config language
        user = User.find_by_login(@user_session.login)
        logger.info 'User config language : '+user.language
        I18n.locale = user.language
        
        # redirect_back_or_default account_url
        redirect_to :action => :index , :controller => :main
        entry.result = 'success'
      else
        entry.result = 'fail'
        render :action => :new
      end

    rescue
      entry.result = 'fail'
    ensure
    entry.ip = request.remote_ip
    entry.save
    end

  end

  def destroy
    entry = Entry.new
    begin
      entry.action = 'logout'
      entry.login = @current_user.login
      
      current_user_session.destroy
      flash[:notice] = "Logout successful!"
      # redirect_back_or_default new_user_session_url
      redirect_to :action => :index , :controller => :main
      
      entry.result = 'success'
    rescue
      entry.result = 'fail'
    ensure
      entry.ip = request.remote_ip
      entry.save
    end

  end
  
end
